%% How to use this script
% Inputs need to be:
% mainDir = the directory with all the folders that contain the images
% patientExcelRow = the row number in the excel sheet that corresponds to the
% patient. To do all the patients please enter 'all'
% scoreRed = the score for a red component. If this is higher than the
%   scoreIR than the red component image is chosen. Please use 1 as the
%   high score and 0 as the low score.
% scoreIR = the score for a IR. If this is higher than the scoreRed than
% the IR image is chosen
% otherImg = a string of either YELLOW or GREEN depending on the analysis
% you want to do
% infoStorage = where you want the excel sheets and images to go. You must
% place them in a new folder before running another test
% centersExcelSheet = the excel sheet that will be used to read in the center data
% excelDataStorageName = the name of the excel sheet your want the data to
% write too. Give it a descriptive name that include s the Date and what
% image sets it uses (Ex: 'Blue vs Green Data October 8')
mainDir = 'D:\Mac Pig GUI Project\Image Sets\Multispect Patients';
patientExcelRow = 'all';
SCORE_RED_COMPONENT = 1;
SCORE_IR = 0;
otherImg = 'GREEN';
infoStorage = 'D:\Mac Pig GUI Project\Algorithm Results\Multispect Patients\October\October 6 B vs Y';
centersExcelSheet = 'Full Fovea and Mac Radius Data.xls';
excelDataStorageName = 'Blue vs Green Data October 8';
[~, ~, raw] = xlsread(centersExcelSheet);

%% Script for running through one image in the GUI computation with save output

% Read in excel sheet first in order to extract patient ID, fovea
% center, and mac radius. the patient ID will be used to select the images
% since the folder organization allows for this.


% Define the main folder that contains all the patient folders. This will
% be the folder being looped through
cd(mainDir)

if strcmp(patientExcelRow, 'all')
    patientExcelRow = 2:length(raw);
end

% Write a for loop that selects a different row in the excel sheet and
% imports the patient ID, fov center, and mac radius. Loop through the rows

for i = patientExcelRow
    % Start clock to measure time to perform one iteration
    timeTotalStart = tic;
    % Isolate specific patients data
    patientInfo = raw(i,:);
    
    % Partion patients data into respective cells and convert cells into proper
    % classes of char or numeric array.
    patientID = char(patientInfo(1)); %Converts cell to class char
    fovRow = cell2mat(patientInfo(2));
    fovCol = cell2mat(patientInfo(3));
    opDiskRow = cell2mat(patientInfo(5));
    opDiskCol = cell2mat(patientInfo(6));
   
    % Select patient directory and images
    workDir = [mainDir filesep patientID];
    
% Select the red image in the patient folder based on file ranking
    redDirFiles = dir(workDir);
    numPotentialRedFiles = length(redDirFiles);
    
    % Pre allocate a weighting score and a best index. The idea is to rank
    % the red component as the highest, the IR as the middle, and the none
    % as the lowest. Use the best Index to generate the red img file
    RED_IM_RANKING = -1;
    BEST_RED_IM = -1;
    for i = 1:numPotentialRedFiles
        if strcmp(redDirFiles(i).name, 'red component.tif')
            score = SCORE_RED_COMPONENT;
        elseif strcmp(redDirFiles(i).name, 'IR.tif')
            score = SCORE_IR;
        else
            score = -1;
        end
        if score > RED_IM_RANKING
            BEST_RED_IM = i;
            RED_IM_RANKING = score;
        end
    end
    
    % Check that a plausible image was chosen for the red image
    if RED_IM_RANKING < 0
        error('Please rename a red image file as red component of IR. It should be a tif file')
    end
    
    redImFiles = [workDir filesep redDirFiles(BEST_RED_IM).name];
    
    % Generate blue and other image paths
    blueImFiles = [workDir filesep 'BLUE'];
    otherImFiles = [workDir filesep otherImg]; %Change between YELLOW or GREEN
    
    % Define selected_method and background_adjustment_image.
    selectedMethod = ['BLUE vs ' otherImg];
    backgroundAdjustmentIm = char(redDirFiles(BEST_RED_IM).name);
    
    % Pre op images and compute average image. This also formats the images
    % into doubles, which is necessary for the algorithm.
    imageSet.blueIm = computeDirAvgImage(blueImFiles, '*.tif', 'dir');
    imageSet.otherIm = computeDirAvgImage(otherImFiles, '*.tif', 'dir');
    % Below is just for a single red image that turns the image into
    % double.
    imageSet.redIm = computeDirAvgImage(redImFiles, '*.tif', 'file');
    
     %Check to make sure image are all the same size.
    if size(imageSet.blueIm) ~= size(imageSet.otherIm)
        error('Please choose blue and other images that are registered together and have the same size')
    elseif size(imageSet.blueIm) ~= size(imageSet.redIm)
        error('Please choose blue and red images that are registered together and have the same size')
    end
    
    % Find macular data 4 degrees from the fovea
    degreesFromFov = 4;
    [ imageFeatures ] =...
    computeMacularData(fovRow, fovCol, opDiskRow, opDiskCol, imageSet.blueIm, degreesFromFov);
   
    % Define contrast region
    imageFeatures.iContrastRegion = imageFeatures.iMacBoundary; %Selects the 4 degree boundary
    
    % Normalize the iamges
    normalizedImSet = imNormalizer(imageSet, imageFeatures, 1/2);
    % Run mac pig algorithm for variable, uniform, and no correction for
    % the user selected centers.
    timeUserVariableStart = tic;
    [variableRatioIm variableRgbMpMap variableQuantityData plotDataVarCorrected scoreMatrix.userVariable]...
        = runMacPigAlgorithm(normalizedImSet, imageFeatures, 'Variable', 'User');
    timeUserVariableEnd = toc(timeUserVariableStart)
    disp('User Variable done')
    [uniformRatioIm uniformRgbMpMap uniformQuantityData plotDataUniformCorrected scoreMatrix.userUniform]...
        = runMacPigAlgorithm(normalizedImSet, imageFeatures, 'Uniform', 'User');
    [ uncorrectedRatioIm uncorrectedRgbMpMap uncorrectedQuantityData plotDataUncorrectedRatio]...
        = runMacPigAlgorithm(normalizedImSet, imageFeatures, 'Uncorrected', 'User');
    
    % Re-find centers based on the macular pigment map
    [variableMapFovRow variableMapFovCol] = findMpMapCenter(variableRatioIm, imageFeatures);
    [uniformMapFovRow uniformMapFovCol] = findMpMapCenter(uniformRatioIm, imageFeatures);
    [uncorrectedMapFovRow uncorrectedMapFovCol] = findMpMapCenter(uncorrectedRatioIm, imageFeatures);
    
    % Re-compute macular data for the new centers. This will be used to re-run
    % the algorithm.
    degreesFromFov = 4;
    % Variable Macular Data and redefined imageFeatures
    [imageFeaturesVariable] = computeImageFeatures...
        (variableMapFovRow, variableMapFovCol, opDiskRow,...
        opDiskCol, imageSet.blueIm, degreesFromFov);
    % Redefine the iContrast Regions. Use the same contrast regions as the user
    % selected center used
    imageFeaturesVariable.iContrastRegion = imageFeatures.iContrastRegion;
    
    % Uniform Macular Data and redefined imageFeatures
    [ imageFeaturesUniform] = computeMacularData...
        (uniformMapFovRow, uniformMapFovCol, opDiskRow,...
        opDiskCol, imageSet.blueIm, degreesFromFov);
    % Redefine the iContrast Regions. Use the same contrast regions as the user
    % selected center used
    imageFeaturesUniform.iContrastRegion = imageFeatures.iContrastRegion;
    
    % Uncorrected Macular Data and redefined imageFeatures
    [imageFeaturesUncorrected] = computeMacularData...
        (uncorrectedMapFovRow, uncorrectedMapFovCol, opDiskRow,...
        opDiskCol, imageSet.blueIm, degreesFromFov);
    % Uncorrected Macular Data and redefined imageFeatures
    imageFeaturesUncorrected.iContrastRegion = imageFeatures.iContrastRegion;
    
    %Re-run the algorithm with the new macular data
    %Variable
    timeMpVariableStart = tic;
    [ variableMpRatioIm variableMpRgbMpMap variableMpQuantityData variableMpPlotData scoreMatrix.mpVariable]...
        = runMacPigAlgorithm(normalizedImSet, imageFeaturesVariable, 'Variable', 'Mp');
    timeMpVariableEnd = toc(timeMpVariableStart)
    disp('Mp Variable done')
    % Uniform
    [ uniformMpRatioIm uniformMpRgbMpMap uniformMpQuantityData uniformMpPlotData scoreMatrix.mpUniform]...
        = runMacPigAlgorithm(normalizedImSet, imageFeaturesUniform, 'Uniform', 'Mp');
    % Uncorrected
    [ uncorrectedMpRatioIm uncorrectedMpRgbMpMap uncorrectedMpQuantityData uncorrectdMpPlotData]...
        = runMacPigAlgorithm(normalizedImSet, imageFeaturesUncorrected, 'Uncorrected', 'Mp');
    
    % Generate a cell structure containing the quality data. This is universal
    % for all corrections
    
    timeTotalEnd = toc(timeTotalStart);
    qualityData = {'Patient ID', 'Method', 'Red Image Used', 'Time (s)'; patientID,...
        otherImg, redDirFiles(BEST_RED_IM).name, timeTotalEnd};
    
    % Combine the quality with the quantity data to form a full data set. Store
    % this in a structure object that will be used later to write out multiple
    % sheets to an excel file
    
    fullData.userVariable = [qualityData, variableQuantityData];
    fullData.userUniform = [qualityData, uniformQuantityData];
    fullData.userUncorrected = [qualityData, uncorrectedQuantityData];
    fullData.mpVariable = [qualityData, variableMpQuantityData];
    fullData.mpUniform = [qualityData, uniformMpQuantityData];
    fullData.mpUncorrected = [qualityData, uncorrectedMpQuantityData];
    
    % In the GUI
%     % Store the data from the analysis in the TEMP folder to that patient
%     [patientBeginPath patientFolder] = fileparts(handles.patientFolderPath);
%     infoStorage = [handles.patientFolderPath filesep 'TEMP'];
%     cd(infoStorage); %Change to the new direct

    % For automation
    mkdir(infoStorage, num2str(patientID));
    cd([infoStorage filesep num2str(patientID)])
        
    % Name the excel workbook that the data will be saved in and generate the
    % list of sheet names.
    excelWorkbookName = [char(patientID) '_data.xls'];
    worksheetNames = fieldnames(fullData);
    % Create an excel sheet
    for i = 1:length(worksheetNames)
        fieldData = getfield(fullData, char(worksheetNames(i)));
%         sheetName = worksheetNames(i);
        xlswrite(excelWorkbookName, fieldData, i);
    end
    
    % Save excel workbook with scoreMatrix data
    excelScoreMatrixName = [char(patientID) '_scoreMatrix_data.xls'];
    worksheetScoreMatrixNames = fieldnames(scoreMatrix);
    for k = 1:length(worksheetScoreMatrixNames)
        fieldDataScorMatrix = getfield(scoreMatrix, char(worksheetScoreMatrixNames(k)));
        xlswrite(excelScoreMatrixName, fieldDataScorMatrix, k);
    end
    
    % Save macular pigment maps for both user and MP center, uniform and
    % variable
    imwrite(variableRgbMpMap, [patientID '_Variable Map_user_center.tif'], 'tif');
    imwrite(uniformRgbMpMap, [patientID '_Uniform Map_user_center.tif'], 'tif');
    imwrite(variableMpRgbMpMap, [patientID '_Variable Map_MP_center.tif'], 'tif');
    imwrite(uniformMpRgbMpMap, [patientID '_Uniform Map_MP_center.tif'], 'tif');
    
    % Save the user center macular pigment plot
    overlayFig = figure('Menu', 'none', 'Toolbar', 'none', 'Units', 'normalized', 'Position',...
        [-1000 -1000 1 1]);
    plot(plotDataVarCorrected, 'r')
    hold on
    plot(plotDataUniformCorrected, 'b')
    plot(plotDataUncorrectedRatio, 'g')
    legend('Red Refl Corr', 'Baseline Corr', 'Uncorrected', 'Location', 'BestOutside')
    xlabel('Relative Distance from Fovea in Pixels');
    ylabel('Radial Average of MP Map');
    title('User Center Graph');
    hold off
    saveas(overlayFig, [patientID '_Rscan_user_center.tif']);
    delete(overlayFig);
    
    % Save the MP center macular pigment plot
    overlayFig = figure('Menu', 'none', 'Toolbar', 'none', 'Units', 'normalized', 'Position',...
        [-1000 -1000 1 1]);
    plot(variableMpPlotData, 'r')
    hold on
    plot(uniformMpPlotData, 'b')
    plot(uncorrectdMpPlotData, 'g')
    legend('Red Refl Corr', 'Baseline Corr', 'Uncorrected', 'Location', 'BestOutside')
    xlabel('Relative Distance from Fovea in Pixels');
    ylabel('Radial Average of MP Map');
    title('MP Center Graph');
    hold off
    saveas(overlayFig, [patientID '_Rscan_MP_center.tif']);
    delete(overlayFig);
    
    disp([patientID ' is done'])
end

disp('Analysis is done')
%%
% New excel import
foldersWithExcel = raw(:,1);
dataCellRange = 'A2:S2';
headerCellRange = 'A1:S1';
% Read in the data

% Generate name of sheets to be used in xlsread
[status, sheets] = xlsfinfo([infoStorage filesep char(foldersWithExcel(2))...
    filesep char(foldersWithExcel(2)) '_data']);
%%
%Generate the headers
count = 1;
for sheetName = sheets
    [~, ~, headers] = xlsread([infoStorage filesep char(foldersWithExcel(2))...
    filesep char(foldersWithExcel(2)) '_data'], char((sheetName)), headerCellRange);
    masterHeaders(:,:,count) = headers;
    count = count + 1;
end
%%
[~, ~, headers] = xlsread([infoStorage filesep char(foldersWithExcel(2))...
    filesep char(foldersWithExcel(2)) '_data'], char(sheets(1)), headerCellRange);

% Generate the first part of the masterExcelWorkbookData

count = 1;
for sheetName = sheets
    [~, ~, excelWorksheetData] = xlsread([infoStorage filesep... 
        char(foldersWithExcel(2)) filesep...
        char(foldersWithExcel(2)) '_data'],...
        char(sheetName), dataCellRange);
    masterExcelWorkbookData(:,:,count) = excelWorksheetData;
    count = count + 1;
end

% Run through all the folders
nFiles = length(foldersWithExcel);
for patientPlaceHolder = 3:16
    excelFilePath = [infoStorage filesep... 
        char(foldersWithExcel(patientPlaceHolder)) filesep...
        char(foldersWithExcel(patientPlaceHolder)) '_data'];
    sheetCount = 1; 
    for sheetName = sheets
    [~, ~, excelWorksheetData] = xlsread(excelFilePath,...
        char(sheetName), dataCellRange);
    fullExcelWorkbookData(:,:,sheetCount) = excelWorksheetData;
    sheetCount = sheetCount + 1;
    disp(sheetCount);
    end
    masterExcelWorkbookData = [masterExcelWorkbookData; fullExcelWorkbookData];
    disp(raw(patientPlaceHolder,1))
end
%%
for patientPlaceHolder = 17:32
    excelFilePath = [infoStorage filesep... 
        char(foldersWithExcel(patientPlaceHolder)) filesep...
        char(foldersWithExcel(patientPlaceHolder)) '_data'];
    sheetCount = 1; 
    for sheetName = sheets
    [~, ~, excelWorksheetData] = xlsread(excelFilePath,...
        char(sheetName), dataCellRange);
    fullExcelWorkbookData(:,:,sheetCount) = excelWorksheetData;
    sheetCount = sheetCount + 1;
    disp(sheetCount);
    end
    masterExcelWorkbookData = [masterExcelWorkbookData; fullExcelWorkbookData];
    disp(raw(patientPlaceHolder,1))
end
%%
for patientPlaceHolder = 33:nFiles
    excelFilePath = [infoStorage filesep... 
        char(foldersWithExcel(patientPlaceHolder)) filesep...
        char(foldersWithExcel(patientPlaceHolder)) '_data'];
    sheetCount = 1; 
    for sheetName = sheets
    [~, ~, excelWorksheetData] = xlsread(excelFilePath,...
        char(sheetName), dataCellRange);
    fullExcelWorkbookData(:,:,sheetCount) = excelWorksheetData;
    sheetCount = sheetCount + 1;
    disp(sheetCount);
    end
    masterExcelWorkbookData = [masterExcelWorkbookData; fullExcelWorkbookData];
    disp(raw(patientPlaceHolder,1))
end
%%
for patientPlaceHolder = 49:nFiles
    excelFilePath = [infoStorage filesep... 
        char(foldersWithExcel(patientPlaceHolder)) filesep...
        char(foldersWithExcel(patientPlaceHolder)) '_data'];
    sheetCount = 1; 
    for sheetName = sheets
    [~, ~, excelWorksheetData] = xlsread(excelFilePath,...
        char(sheetName), dataCellRange);
    fullExcelWorkbookData(:,:,sheetCount) = excelWorksheetData;
    sheetCount = sheetCount + 1;
    disp(sheetCount);
    end
    masterExcelWorkbookData = [masterExcelWorkbookData; fullExcelWorkbookData];
    disp(raw(patientPlaceHolder,1))
end
%%
masterExcelWorkbookData = [masterHeaders; masterExcelWorkbookData];
%%
cd(infoStorage)
count = 1;
for i = 1:6
    xlswrite(excelDataStorageName, masterExcelWorkbookData(:,:,count), i)
    count = count + 1
end
